import {action, mutation} from '../../../../common/quantity'
import ipcs from '../../../../common/typeIpcs'
import A from '../../../../common/typeActions'
import commonServer from '../../../../server/common/commonServer'
import SQLite from '../../../../common/SQLiteHelper'
// import common from '../../../common/common'
import Vue from 'vue'

// const fs = require('fs')

const {
  util: {getEvidenceMaterialTree, getTreeNodes, isArray}
} = require('../../../../util')

const state = {
  caseID: '',
  casePath: '',
  caseInfo: {},
  dossierAllDataSource: {},
  dossierDataSource: [],
  dossierTreeDataSource: [],
  docDossierDataSource: [],
  docDossierTreeDataSource: [],
  retrieveDataSource: []
}

const mutations = {
  setCasePath (state, casePath) {
    if (process.browser) {
      state.caseID = casePath.caseID
      state.casePath = casePath.casePath
    } else {
      state.casePath = casePath
      Vue.prototype.$electron.ipcRenderer.send(ipcs.MAIN.setCasePath, casePath)
    }
  },
  [mutation.appearCourt.openCase] (state, data) {
    try {
      state.caseInfo = data ? data.caseInfo : {}

      state.docDossierDataSource = data ? data.docDossier : []

      state.docDossierTreeDataSource = data ? data.docDossierTree : []
      state.retrieveDataSource = []
    } catch (e) {
      console.error(e)
    }
  },
  [mutation.appearCourt.initDossier] (state, data) {
    data.dossier = data.dossier.sort((a, b) => {
      return a.order - b.order
    })
    if (!data.id) {
      let allDossierSource = {}
      for (let i = 0; i < data.dossierTree.length; i++) {
        let item = data.dossierTree[i]
        allDossierSource[item.NodeID] = this.getters.getDossiers(data.dossier, item.NodeID)

        if (i === 0) state.dossierDataSource = allDossierSource[item.NodeID]
      }
      state.dossierAllDataSource = allDossierSource
      state.dossierTreeDataSource = data ? data.dossierTree : []
    } else {
      let rootNode = state.dossierTreeDataSource.find((x) => {
        return x.NodeID === data.id
      })
      if (rootNode) {
        state.dossierDataSource = data.dossier
        rootNode.children = data.dossierTree
        state.dossierAllDataSource[data.id] = data.dossier
      }
    }
  },
  [mutation.appearCourt.initRetrieveDataSource] (state, data) {
    state.retrieveDataSource = data
  },
  [mutation.appearCourt.getDossierTreeSource] (context, data) {
    state.dossierDataSource = data || []
  },
  [mutation.appearCourt.setData] (state, data = {}) {
    for (let key in data) {
      state[key] = data[key]
      let temp = isArray(data[key]) ? data[key] : [data[key]]
      let nodes = getTreeNodes(temp)
      if (key === 'dossierTreeDataSource') {
        state.dossierDataSource = nodes
      }
      if (key === 'docDossierTreeDataSource') {
        state.docDossierDataSource = nodes
      }
    }
  },
  [mutation.appearCourt.setDossierTreeSource] (state, obj) {
    if (obj.id) {
      for (let i = 0; i < obj.delNode.length; i++) {
        let index = state.dossierDataSource.findIndex((x) => {
          return x.ID === obj.delNode[i].ID
        })
        if (index >= 0) state.dossierDataSource.splice(index, 1)
      }
      state.dossierAllDataSource[obj.id] = state.dossierDataSource
      let dossier = state.dossierTreeDataSource.find((x) => {
        return x.NodeID === obj.id
      })
      if (dossier) dossier.children = obj.data
    }
    // else {
    //   state.dossierTreeDataSource = obj.data;
    // }
  },

  [mutation.appearCourt.closeCase] (state, data) {
    this._vm.$electron.ipcRenderer.send(ipcs.MAIN.setCasePath, '')
    // Vue.prototype.$electron.ipcRenderer.send(ipcs.MAIN.setCasePath, casePath)
    state.casePath = ''
    state.caseInfo = {}
    state.dossierAllDataSource = {}
    state.dossierDataSource = []
    state.dossierTreeDataSource = []
    state.docDossierDataSource = []
    state.docDossierTreeDataSource = []
    state.retrieveDataSource = []
    this.commit(mutation.preplan.initPrePlan, [])
    if (!process.browser) {
      this.commit(mutation.container.setCurrPage, 1)
      // this.commit('clearEvidenceCatalogTreeData', []);
    }
  },
  [mutation.appearCourt.delDossiers] (state, index) {
    state.dossierTreeDataSource.splice(index, 1)
  }
}

const actions = {
  async [action.appearCourt.initAppearCourt] ({commit, dispatch}) {
    try {
      this._vm.$logger.info('开始加载案件信息...')
      commit('SET_LOADINGCASE', {loading: true, loadingText: '正在加载案件信息，请稍候...'})
      let caseInfo = await commonServer.getCaseInfo()
      this._vm.$logger.info('案件信息加载完成...')
      await dispatch(action.appearCourt.initDossier)
      this._vm.$logger.info('开始加载文书卷宗...')
      commit('SET_LOADINGCASE', {loading: true, loadingText: '正在加载文书卷宗，请稍候...'})
      let docDossier = await commonServer.getDocDossierSource()
      this._vm.$logger.info('文书卷宗加载完成...')
      this._vm.$logger.info('开始组织文书结构...')
      commit('SET_LOADINGCASE', {loading: true, loadingText: '正在组织文书卷宗，请稍候...'})
      let docDossierTree = getEvidenceMaterialTree(docDossier)
      this._vm.$logger.info('文书结构组织完成...')
      // let retrieveData = []
      await dispatch(action.preplan.getCatalogTemplate)

      commit(mutation.appearCourt.openCase, {
        caseInfo,
        docDossier,
        docDossierTree
      })

      await dispatch(A.SLIDEEDITOR.GetEditorCofing)
      commit(mutation.container.setCurrPage, 2)
    } catch (e) {
      console.error(e)
      this._vm.$alert(e.message, '案件打开错误', {type: 'error'})
      throw e
    } finally {
      commit('SET_LOADINGCASE', {loading: false})
    }
  },
  /**
   * 打开案件
   * @param commit
   * @param dispatch
   * @param path
   * @param data
   */
  async [action.appearCourt.openCase] ({commit, dispatch}, path) {
    this.commit('setCasePath', path)

    // if (process.browser) await dispatch(A.COMMON.UpdateDBFile, path.casePath)

    // 加载书签
    await dispatch(action.bookmark.getBookmark)
    //
    // 加载案件文件信息
    await dispatch(action.appearCourt.initAppearCourt)

    // 跳转页面
  },

  async [action.appearCourt.initDossier] (context, id = '') {
    try {
      context.commit('SET_LOADINGCASE', {loading: true, loadingText: '正在加载电子卷宗，请稍候...'})
      this._vm.$logger.info('开始加载电子卷宗...')
      let dossier = await commonServer.getDossierSource(id)
      this._vm.$logger.info('电子卷宗加载完成...')
      this._vm.$logger.info('开始组织电子卷宗结构...')
      context.commit('SET_LOADINGCASE', {loading: true, loadingText: '正在组织电子卷宗，请稍候...'})
      let dossierTree = getEvidenceMaterialTree(dossier, id, 0)
      this._vm.$logger.info('电子卷宗结构组织完成...')
      context.commit(mutation.appearCourt.initDossier, {id, dossier, dossierTree})
      return {dossier, dossierTree}
    } catch (ex) {
      this._vm.$alert(ex.message, '加载电子卷宗异常')
    } finally {
      context.commit('SET_LOADINGCASE', {loading: false})
    }
  },
  async [action.appearCourt.initRetrieveDataSource] (context, obj) {
    try {
      context.commit('SET_LOADINGCASE', {loading: true, loadingText: '正在检索关键字，请稍候...'})

      this._vm.$logger.info('开始检索全案检索内容...')
      let data = await commonServer.getRetrieveData(obj.type, obj.value)
      this._vm.$logger.info('全案检索内容检索完成...')
      return data
    } catch (ex) {
      console.log(ex)
      this._vm.$alert(ex.message, '加载全案检索内容异常')
    } finally {
      context.commit('SET_LOADINGCASE', {loading: false})
    }
  },

  async [action.appearCourt.getDossierTreeSource] (context, id = '') {
    let dossier = context.state.dossierTreeDataSource.find((x) => {
      return x.NodeID === id && x.children
    })
    if (!dossier) {
      dossier = (await context.dispatch(action.appearCourt.initDossier, id)).dossierTree
    } else {
      dossier = dossier.children
    }
    context.commit(mutation.appearCourt.getDossierTreeSource, context.state.dossierAllDataSource[id])
    return dossier
  },
  async [action.appearCourt.setDossierTreeSource] (context, obj) {
    context.commit(mutation.appearCourt.setDossierTreeSource, obj)
  },
  async [action.appearCourt.closeCase] ({commit, dispatch}, data) {
    dispatch(A.SLIDEEDITOR.ClearSlideEditor)
    commit(mutation.appearCourt.closeCase)
  },
  async [action.appearCourt.delDossiers] ({commit}, id) {
    try {
      commit('SET_LOADINGCASE', {loading: true, loadingText: '正在删除电子卷宗，请稍候...'})
      SQLite.DelEvidenceMaterial(id)
      // await commonServer.delDossiers(id)
      let dossierID = ''
      let index = state.dossierTreeDataSource.findIndex(x => x.ID === id)
      if (index + 1 < state.dossierTreeDataSource.length) dossierID = state.dossierTreeDataSource[index + 1].ID
      if (!dossierID && index - 1 >= 0) dossierID = state.dossierTreeDataSource[index - 1].ID
      commit(mutation.appearCourt.delDossiers, index)
      return dossierID
    } catch (e) {
      console.error('删除电子卷宗异常', e)
      throw e
    } finally {
      commit('SET_LOADINGCASE', {loading: false})
    }
  }
}

const getters = {
  dossierRootNode: (state) => {
    let root = []
    for (let i = 0; i < state.dossierTreeDataSource.length; i++) {
      let item = state.dossierTreeDataSource[i]
      root.push({
        ID: item.ID,
        NodeID: item.NodeID,
        NodeParentID: item.NodeParentID,
        MLXSMC: item.MLXSMC
      })
    }
    return root
  },
  // 获取卷宗文件
  fileDataSource: (state) => {
    return state.dossierDataSource.filter((item) => {
      return item.FileType === 'file'
    })
  },
  // 获取文书文件
  docFileDataSource: (state) => {
    return state.docDossierDataSource.filter((item) => {
      return item.FileType === 'file'
    })
  },
  isFirstNode: (state, getter) => (rootID, index) => {
    return index < 0
    // let rootOrder = 0
    // let dataSource = []
  },
  isLastNode: (state, getter) => (rootID, index) => {
    return getter.fileDataSource.length - 1 < index

    // let rootOrder = 0
    // let dataSource = []
    // if (index < 0) return true
    // if (rootID) {
    //   dataSource = getter.fileDataSource
    //   let rootNodes = getter.dossierRootNode
    //   let rootIndex = rootNodes.findIndex(x => {
    //     return x.NodeID === rootID
    //   })
    //   if (rootIndex < 0) return true
    //   rootOrder = rootNodes.length - 1 > rootIndex ? rootNodes[rootIndex + 1].order : dataSource[dataSource.length - 1].order
    // } else {
    //   dataSource = getter.docFileDataSource
    //   if (!dataSource || !dataSource.length) return true
    //
    //   rootOrder = dataSource[dataSource.length - 1].order
    // }
    // if (dataSource.length - 1 < index) return true
    // return dataSource[index].order > rootOrder
  },
  getDossiers: (state, getter) => (dataSource, NodeParentID) => {
    let arr = []
    dataSource.filter((x) => {
      return x.NodeParentID === NodeParentID
    }).forEach((x) => {
      arr.push(x)
      if (x.FileType === 'dir') arr = arr.concat(getter.getDossiers(dataSource, x.NodeID))
    })
    return arr
  }
}

export default {
  state,
  mutations,
  actions,
  getters
}
